<template>
  <h1>一个简单的右拉伸指令v-resize.right：</h1>
  <div class="container">
    <div class="left" v-resize.right></div>
    <div class="right"></div>
  </div>
</template>

<script lang="ts" setup>
const vResize = {
  mounted(el: HTMLElement, binding: any) {
    console.log(binding);
    el.addEventListener('pointermove', (e: PointerEvent) => {
      const { right } = el.getBoundingClientRect()
      const { clientX } = e
      if (right - clientX < 8) {
        el.style.cursor = 'col-resize'
      } else {
        el.style.cursor = ''
      }
    })
    el.addEventListener('pointerdown', (e: PointerEvent) => {
      const rightDom = el.nextElementSibling as HTMLElement // 获取右节点
      const startX = e.clientX // 获取当前点击坐标

      const { width } = el.getBoundingClientRect() // 获取当前节点宽度
      const { width: nextWidth } = rightDom.getBoundingClientRect() // 获取右节点宽度
      el.setPointerCapture(e.pointerId) // HTML5 的 API 自行百度~
      el.style.borderRight = '1px solid yellow'

      const MIN_WIDTH = 10
      const onDocumentMouseMove = (e: MouseEvent) => {
        const offsetX = e.clientX - startX // 此时的 x 坐标偏差
        if (width + offsetX < MIN_WIDTH || nextWidth - offsetX < MIN_WIDTH) {
          return
        }
        // 更新左右节点宽度
        el.style.width = width + offsetX + 'px'
        rightDom.style.width = nextWidth - offsetX + 'px'
      }
      // 因为此时我们要在整个屏幕移动 所以我们要在 document 挂上 mousemove
      document.addEventListener('mousemove', onDocumentMouseMove)
      el.addEventListener('pointerup', (e: PointerEvent) => {
        // el.releasePointerCapture(e.pointerId) // 会在pointerup中自动释放
        el.style.borderRight = 'none'
        document.removeEventListener('mousemove', onDocumentMouseMove)
      })
    })

  }
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  width: 400px;
  height: 100px;

  >div {
    // float: left;
    // height: 100%;
    width: 50%;
  }
}

.left {
  background-color: lightcoral;
}

.right {
  background-color: lightblue;
}
</style>